package com.mozz.finally_work.servlet;

import com.mozz.finally_work.dao.BlogDao;
import com.mozz.finally_work.dao.UserDao;
import com.mozz.finally_work.pojo.Category;
import com.mozz.finally_work.pojo.Tag;
import com.mozz.finally_work.pojo.User;
import com.mozz.finally_work.utils.MybatisUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.ibatis.session.SqlSession;
import sun.misc.BASE64Encoder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "UpdateUserInfoServlet", value = "/UpdateUserInfoServlet")
public class UpdateUserInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SqlSession session = MybatisUtils.getSession();
        UserDao dao = session.getMapper(UserDao.class);

        // 图片上传
        // 使用fileupload组件完成文件上传
        // 上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/avatar");
        // 判断，该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            // 创建该文件夹
            file.mkdirs();
        }

        // 解析request对象，获取上传文件项
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        String id = null;
        String nickName = null;
        String email = null;
        String password = null;
        String filename = null;
        List<Tag> tags = new ArrayList<>();
        List<Category> categories = new ArrayList<>();
        // 解析request
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(request);
            // 遍历
            for (FileItem item : items) {
                // 进行判断，当前item对象是否是上传文件项
                if (item.isFormField()) {
                    // 说明普通表单
                    String fieldName = item.getFieldName();
//                    if (item.getString("UTF-8") == null || item.getString("UTF-8").trim().equals("")) {
//                        response.sendRedirect("index.jsp");
//                        return;
//                    }
                    System.out.println(fieldName);
                    if (fieldName.equals("nickName")) {
                        nickName = item.getString("UTF-8");
                    } else if (fieldName.equals("email")) {
                        email = item.getString("UTF-8");
                    } else if (fieldName.equals("id")) {
                        id = item.getString("UTF-8");
                        if (id.equals("")) {
                            response.sendRedirect("index.jsp");
                            return;
                        }
                    } else if (fieldName.equals("password")) {
                        password = item.getString("UTF-8");
                    }

                } else {
                    // 说明上传文件项
                    // 获取上传文件的名称
                    filename = item.getName();
                    if (!filename.equals("")) {
                        // 把文件的名称设置唯一值，uuid
                        String coverUuid = UUID.randomUUID().toString().replace("-", "");
                        filename = coverUuid + "_" + filename;
                        // 完成文件上传
                        item.write(new File(path, filename));
                        // 删除临时文件
                        item.delete();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        User user = new User();
        if (!id.equals("")) {
            user.setId(id);
        }
        if (!nickName.equals("")) {
            user.setNickName(nickName);
        }
        if (!email.equals("")) {
            user.setEmail(email);
        }
        if (!password.equals("")) {
//            MD5加密
            // 密码md5加密
            MessageDigest md = null;
            String newPassword = null;
            try {
                md = MessageDigest.getInstance("MD5");
                BASE64Encoder encoder = new BASE64Encoder();
                newPassword = encoder.encode(md.digest(nickName.getBytes()));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            user.setPassword(newPassword);
        }
        if (!filename.equals("")) {
            user.setAvatar(filename);
        }

        Integer result = dao.updateUser(user);
        session.commit();
        session.close();
        response.sendRedirect("UserHomeServlet?userId="+id);
    }
}
